package com.yin.myproject.zk.recipes.lock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Eason
 * @create 2018-04-12 11:18
 **/
public class ZookeeperUtils implements Watcher {

    private ZooKeeper zooKeeper;

    private String connectString;
    private int sessionTimeout;
    private CountDownLatch connectedSignal = new CountDownLatch(1);


    public ZookeeperUtils(String connectString, int sessionTimeout) {
        this.connectString = connectString;
        this.sessionTimeout = sessionTimeout;
        try {
            zooKeeper = new ZooKeeper(connectString, sessionTimeout, this);
            connectedSignal.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void process(WatchedEvent event) {
        //建立连接用
        if (event.getState() == Event.KeeperState.SyncConnected) {
            System.out.println(Thread.currentThread().getName() + " :zk connected success");
            connectedSignal.countDown();
            return;
        }
    }

    public ZooKeeper getZk() {
        return zooKeeper;
    }

}
